﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Flower.Logging.Sinks
{
    /// <summary>
    /// Simple file logging sink.
    /// 
    /// Normally, the logging to file is performed via external logging frameworks.
    /// This sink is used only if the log manager has failed to initialize.
    /// </summary>
    public class FileLogSink : ILogSink
    {
        private readonly string _fileName;

        public FileLogSink(string fileName)
        {
            _fileName = fileName;
        }

        public void Dispatch(LogEntry entry)
        {
            using (var file = new StreamWriter(_fileName, true, Encoding.UTF8))
            {
                if (entry.Exception == null)
                {
                    file.WriteLine("{0} {1} [{2}]: {3}", entry.Severity, entry.Timestamp, entry.Source, entry.Message);
                }
                else
                {
                    file.WriteLine("{0} {1} [{2}]: {3}\n{4}", entry.Severity, entry.Timestamp, entry.Source, entry.Message, entry.Exception);
                }
            }
        }

        public void Flush()
        {
        }
    }
}
